package helper;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo {
    public static void main(String[] args) {
        //线程数量
        Semaphore semaphore = new Semaphore(3);

        for(int i = 0 ; i < 6 ; i++){
            new Thread(()->{
                try {
                    //获取许可证 acquire()
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"取得信号量。");
                    TimeUnit.SECONDS.sleep(2);
                    //释放许可证，将其返回到信号量。  release()
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    semaphore.release();
                    System.out.println(Thread.currentThread().getName()+"释放信号量。");
                }
            }).start();
        }
    }
}
